const express = require('express'); 
const pool = require('../pool');
const router = express.Router();

router.get('/list',(req,res,next)=>{
    let obj = req.obj;
    console.log(obj);
    pool.query('select title,count,img,src,product_cat.tag,product_cat.cid from product,product_cat where cat_id=cid',(err,r)=>{
        if(err){
            return next(err);
        };
        
        res.send({code:200,msg:'',data:reArr(r)})
    })
});

router.get('/dail',(req,res,next)=>{
    let obj = req.obj;
    console.log(obj);
    pool.query('select cname,count,count2,p,p2,c_img,product_deail.pname,product_deail.pen,product_deail.p_id from product_count,product_deail where c_id=p_id',(err,r)=>{
        if(err){
            return next(err);
        };
        
        res.send({code:200,msg:'',data:reDail(r)})
    })
});

function reArr(r){
    let  obj= {};
    let arr = [];
    let num = 0;
    r.forEach((item,index) => {
        if(num!=item.cid){
            arr= [];
            let o = {tag:item.tag+'-'+item.title,msg:{
                title:`这是${item.tag}-${item.title}`,
                count:item.count,
                img:item.img,
                src:item.src
            }}
            arr.push(o)
            obj[`我们的产品${item.tag}`] = arr;
        }else{
            let o = {tag:item.tag+'-'+item.title,msg:{
                title:`这是${item.tag}-${item.title}`,
                count:item.count,
                img:item.img,
                src:item.src
            }}
            arr.push(o)
            obj[`我们的产品${item.tag}`] = arr;
        }
        num=item.cid;
       
    });
    return obj;
    //res.send({code:200,msg:'',data:r})
};

function reDail(r){
    let obj = { };
    let arr = [];
    let b = [];
    let num = 0;
    r.forEach((v,i)=>{
      
        if(num!=v.p_id){
            i++;
            arr = [];
            obj = {};
            let o = {
                title:v.cname,
                p:v.p,
                count:v.count,
                p2:v.p2,
                count2:v.count2,
                img:v.c_img
            };
            arr.push(o);
            obj.title = v.pname;
            obj.en = v.pen;
            obj.msg = arr;
            b.push(obj)
        }else{
            let o = {
                title:v.cname,
                p:v.p,
                count:v.count,
                p2:v.p2,
                count2:v.count2,
                img:v.c_img
            };
            arr.push(o);
        }
        num=v.p_id;
       
    });
   
    return b;
}

module.exports = router;